package hse.jack.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;
import org.nutz.log.Log;
import org.nutz.log.Logs;

/**
 * <b>操作word document工具类</b>
 * 
 * @author jackLiang
 * @date 2013年1月31日16:25:19
 * @version 1.0
 */
public class WordDocumentUtil {
	private static final Log log = Logs.get();

	/**
	 * 写入下载word
	 * 
	 * @param path
	 * @param response
	 * @param request
	 */
	public static void writeWordDocument(String fileName,
			HttpServletResponse response, HttpServletRequest request) {
		InputStream is = null;
		ServletOutputStream servletOS = null;
		// 文件保存路径
		String fileDir = request.getSession().getServletContext()
				.getRealPath("/upload/word");
		try {
			is = new FileInputStream(new File(fileDir + "/" + fileName));
			HWPFDocument hdt = new HWPFDocument(is);
			Fields fields = hdt.getFields();
			Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN)
					.iterator();
			while (it.hasNext()) {
				System.out.println(it.next().getType());
			}
			// 替换读取到的word模板内容的指定字段
			Range range = hdt.getRange();
			Map<String, String> map = new HashMap<String, String>();
			map.put("title", "通用安全考试试卷");
			map.put("judgeTitle", "通用安全考试试卷111");
			map.put("jiedaTitle", "通用安全考试试卷1");
			map.put("singleTitle", "通用安全考试试卷111111");
			map.put("blog_name", "老k博客");
			map.put("domain_name", "laokboke.net");
			map.put("jack", "我是来打酱油的！！！");
			map.put("description", "是一个专注于wordpress、java、gis、建站、网站推广、seo的IT博客。");
			for (Map.Entry<String, String> entry : map.entrySet()) {
				range.replaceText(entry.getKey(), entry.getValue());
			}

			// 输出word内容文件流，提供下载
			response.reset();
			response.setContentType("application/x-msdownload");
			response.addHeader("Content-Disposition", "attachment; filename="
					+ fileName);
			ByteArrayOutputStream ostream = new ByteArrayOutputStream();
			servletOS = response.getOutputStream();
			hdt.write(ostream);
			servletOS.write(ostream.toByteArray());
			servletOS.flush();
			servletOS.close();
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.error("E!!!!" + e);
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException e) {
				if (log.isDebugEnabled())
					log.error("E!!!!" + e);
			}
		}

	}
}
